package com.quanyan.club.util;

import java.lang.reflect.Method;

/**
 * Created by xian-guo on 2017/3/16.
 */
public class BeanCopy {
    public static void CopyPoperties(Object obj1,Object obj2) throws Exception{
        Class classObj1=obj1.getClass();
        java.lang.reflect.Field[] fieldObj1=classObj1.getDeclaredFields();
        Class classObj2=obj2.getClass();
        for (java.lang.reflect.Field fObj1:fieldObj1){
            boolean fExits=fObj1.isAnnotationPresent(Field.class);
            if (!fExits){//判断字段上该注解是否存在
                continue;
            }
            Field anField=fObj1.getAnnotation(Field.class);
            String anObj2FieldName=anField.value();
            java.lang.reflect.Field[] fieldObj2=classObj2.getDeclaredFields();
            for (java.lang.reflect.Field fObj2:fieldObj2){
                String fObj2FieldName=fObj2.getName();
                if (anObj2FieldName.equals(fObj2FieldName)){//匹配注解对应的字段
                    String obj1FieldName=fObj1.getName();
                    String obj=fObj1.getType().getName();
                    if (obj1FieldName.startsWith("is") && (obj.contains("boolean") || obj.contains("Boolean"))){
                        Method obj2Method=classObj2.getDeclaredMethod(fObj2FieldName);//isFlag,isflag,
                        Object obj2FieldValue= obj2Method.invoke(obj2);
                        String obj1MethodName=null;
                        if (Character.isUpperCase(obj1FieldName.charAt(2))){//is后面大写字母
                            obj1MethodName="set"+obj1FieldName.substring(2);//setFlag,
                        }else{
                            obj1MethodName="set"+fObj1.getName().substring(0,1).toUpperCase()+fObj1.getName().substring(1);//setIsflag
                        }
                        Method fiMethod=classObj1.getDeclaredMethod(obj1MethodName,fObj1.getType());
                        fiMethod.invoke(obj1,obj2FieldValue);
                        break;
                    }
                    String obj2MethodName="get"+fObj2FieldName.substring(0,1).toUpperCase()+fObj2FieldName.substring(1);
                    Method obj2Method=classObj2.getDeclaredMethod(obj2MethodName);
                    Object obj2FieldValue= obj2Method.invoke(obj2);

                    String obj1MethodName="set"+fObj1.getName().substring(0,1).toUpperCase()+fObj1.getName().substring(1);
                    Method fiMethod=classObj1.getDeclaredMethod(obj1MethodName,fObj1.getType());
                    fiMethod.invoke(obj1,obj2FieldValue);
                    break;
                }
            }
        }
    }
}
